package com.yykj.common.aspect;

import com.yykj.common.util.GsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Slf4j
@Order(5)
@Component
public class PerformanceAspect {

    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("execution(public * com.yykj..controller..*.*(..)) " +
            " && !execution(public * com..controller..*.set*(..))  " +
            " && !execution(public * com..controller..*.listAppointDayTimeInfo(..))  " +
            " && !execution(public * com..controller..*.listPatientPrescription(..))  " +
            " && !execution(public * com..controller..*.listDoctorPrescription(..))  " +
            " && !execution(public * com..controller..*.getHospitalDepartment(..))  ")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        request.getHeader("OPTIONS");

        // 记录下请求内容
        log.info("URL : " + request.getRequestURL().toString());
//        log.info("HTTP_METHOD : " + request.getMethod());
//        log.info("IP : " + request.getRemoteAddr());
//        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
        for (Object o :joinPoint.getArgs()){
            log.info("ARGS:{}",GsonUtil.toJson(o));
        }

    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        log.info("RESPONSE : " + GsonUtil.toJson(ret));
        log.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()) + " ms");
    }

}
